package co.fitstart.coach.web.controller.courseware;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.coach.entity.security.Login;
import co.fitstart.coach.service.CourseRoundService;
import co.fitstart.coach.service.CoursewareService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.service.RecordService;
import co.fitstart.coach.service.WeeklyPlanService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.round.RoundCoursewareStatus;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.courseware.exercise.PlannedSchedule;
import co.fitstart.entity.courseware.fitnessgroup.Courseware;
import co.fitstart.entity.courseware.fitnessgroup.FitnessGroup;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.user.StudentTargetData;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.entity.user.inbody.InbodyRecord;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping(value = "/rounds")
public class CoursewareController {    
    
    private static final Logger logger = LoggerFactory.getLogger(CoursewareController.class);
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CoursewareService coursewareService;
    
    @Autowired
    private RecordService recordService;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Autowired
    private WeeklyPlanService weekPlanService;
    
    /**
     * 
     * @param login
     * @param roundCoursewareStatus
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView list(@Secure Login login,
                             @RequestParam(name = "type", required = false, defaultValue = "EDITING") String status) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/list/"  + status.toLowerCase() + "-courseware-list");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        List<CourseRound> courseRounds;
        
        if("CANCEL".equals(status)) {
            courseRounds = courseRoundService.listCancel(coach);
        } else {
            RoundCoursewareStatus roundCoursewareStatus = RoundCoursewareStatus.aliasOf(status);
            
            courseRounds = courseRoundService.list(coach, roundCoursewareStatus);
        }

        modelAndView.addObject("courseRounds", courseRounds);
        modelAndView.addObject("status", status);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @param roundId
     * @param roundCoursewareStatus
     * @return
     */
    @RequestMapping(value = "/{roundId}", method = RequestMethod.GET)
    public ModelAndView detail(@Secure Login login,
                               @PathVariable("roundId") Long roundId,
                               @RequestParam(name = "type", required = true) RoundCoursewareStatus roundCoursewareStatus) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/view/" + roundCoursewareStatus.getAlias() + "-courseware-view");
        
        CourseRound courseRound = courseRoundService.load(CourseRound.class, roundId);
        
        modelAndView.addObject("roundCoursewareStatus", roundCoursewareStatus);
        modelAndView.addObject("courseRound", courseRound);
        
        if(roundCoursewareStatus.isGrouping()) {
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param roundId
     * @param groupId
     * @param tagIds
     * @return
     */
    @RequestMapping(value = "/{roundId}/group", method = RequestMethod.PATCH)
    public @ResponseBody String onGroup(@PathVariable("roundId") Long roundId,
                                        @RequestParam("groupId") Long groupId,
                                        @RequestParam(name = "tagIds", required = false) String tagIds) {
        
        Result result = new Result();
        
        try {
            
            CourseRound courseRound = courseRoundService.load(CourseRound.class, roundId);getClass();
            FitnessGroup fitnessGroup = coursewareService.loadFitnessGroup(groupId);
            
            coursewareService.changeGroup(courseRound, fitnessGroup, tagIds);
            
            result.success().message("分组成功!");
            
        } catch (Exception e) {
            
            logger.error("onGroup - ", e);
            
            result.fail().message("分组失败!");
            
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * 
     * @param roundId
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/{roundId}/edit-group", method = RequestMethod.PATCH)
    public @ResponseBody String onEditGroup(@PathVariable("roundId") Long roundId,
                                            @RequestParam("groupId") Long groupId){
        Result result = new Result();
        
        try {
            
            CourseRound courseRound = courseRoundService.load(CourseRound.class, roundId);
            FitnessGroup fitnessGroup = coursewareService.loadFitnessGroup(groupId);
            
            coursewareService.editGroup(courseRound, fitnessGroup);
            
            result.success().message("更改分组成功");
            
        } catch (Exception e) {
            
            result.fail().message("更改分组失败");
            
            logger.error("#onEditGroup() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * list schedule of courseware
     * 
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundId}/schedules", method = RequestMethod.GET)
    public ModelAndView schedules(@PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/schedule/course-schedule-index");
        
        CourseRound courseRound = courseRoundService.get(CourseRound.class, roundId);
        
        modelAndView.addObject("courseRound", courseRound);
        modelAndView.addObject("courseSchedules", courseRound.getSchedules());
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param roundId
     * @param scheduleId
     * @return
     */
    @RequestMapping(value = "/{roundId}/schedules/{scheduleId}", method = RequestMethod.GET)
    public ModelAndView schedule(@PathVariable("roundId") Long roundId,
                                 @PathVariable("scheduleId") Long scheduleId) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/schedule/course-schedule-detail");
        
        CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, scheduleId);
        
        if(courseSchedule != null) {
            List<Courseware> coursewares = coursewareService.listCourseWares(courseSchedule);
            PlannedSchedule plannedSchedule = weekPlanService.getPlannedSchedule(courseSchedule);
            
            modelAndView.addObject("coursewares", coursewares);
            modelAndView.addObject("plannedSchedule", plannedSchedule);
            modelAndView.addObject("session", coursewareService.getRank(courseSchedule));
            modelAndView.addObject("courseSchedule", courseSchedule);
        }
        
        return modelAndView;
        
    }
    
    /**
     * list inbody data
     * 
     * @return
     */
    @RequestMapping(value = "/{roundId}/inbody-records", method = RequestMethod.GET)
    public ModelAndView inbody(@PathVariable("roundId") Long roundId,
                               @RequestParam(value="scheduleId", required = false) Long scheduleId,
                               @RequestParam(value="back", required = false) String back) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/record/inbody-record-list");
        
        CourseRound courseRound = courseRoundService.get(CourseRound.class, roundId);
        
        List<InbodyRecord> inbodyRecords = recordService.listInbodyRecoreds(courseRound);
        
        modelAndView.addObject("inbodyRecords", inbodyRecords);
        modelAndView.addObject("courseRound", courseRound);
        modelAndView.addObject("scheduleId", scheduleId);
        modelAndView.addObject("back", back);
        
        return modelAndView;
        
    }
    
    /**
     * list bwh record
     * 
     * @return
     */
    @RequestMapping(value = "/{roundId}/bwh-records", method = RequestMethod.GET)
    public ModelAndView bwh(@PathVariable("roundId") Long roundId,
                            @RequestParam(value="scheduleId", required = false) Long scheduleId,
                            @RequestParam(value="back", required = false) String back) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/record/bwh-record-list");
        
        CourseRound courseRound = courseRoundService.get(CourseRound.class, roundId);
        
        List<BwhRecord> bwhRecords = recordService.listBwhRecords(courseRound);
        
        modelAndView.addObject("bwhRecords", bwhRecords);
        modelAndView.addObject("courseRound", courseRound);
        modelAndView.addObject("scheduleId", scheduleId);
        modelAndView.addObject("back", back);
        
        return modelAndView;
        
    }
    
    /**
     * list target
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundId}/target", method = RequestMethod.GET)
    public ModelAndView target(@PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("courseware/record/target-list");
        
        CourseRound courseRound = courseRoundService.get(CourseRound.class, roundId);
        
        List<StudentTargetData> targets = recordService.listTargets(courseRound);
        
        modelAndView.addObject("targets", targets);
        modelAndView.addObject("courseRound", courseRound);
        
        return modelAndView;
        
    }
}
